package 排序.快速排序;

import 排序.IArraySort;

import java.util.Arrays;

/**
 * @author zc
 * @version 1.0
 * @date 2021/9/30 13:31
 *
 * https://blog.csdn.net/nrsc272420199/article/details/82587933
 *
 * https://www.runoob.com/w3cnote/quick-sort-2.html
 */
public class QuickSort implements IArraySort {


    @Override
    public int[] sort(int[] sourceArray) {
        int[] arr = Arrays.copyOf(sourceArray, sourceArray.length);
        return quickSort(arr,0,arr.length-1);
    }

    private int[] quickSort(int[] arr ,int left,int right){
        if(left<right){
            int partition = partition(arr, left, right);
            quickSort(arr,left,partition-1);
            quickSort(arr,partition+1,right);
        }
        return arr;
    }

    private int partition(int[] arr,int left,int right){
        //设定基准值（pivot）
        int pivot = left;
        int index = pivot+1;

        for (int i = index; i <= right; i++) {
            if(arr[i]<arr[pivot]){
                swap(arr,i,index);
                index++;
            }
        }
        swap(arr,pivot,index-1);
        return index-1;
    }


    private void swap(int[] arr,int i,int j){
        int temp = arr[i];
        arr[i]=arr[j];
        arr[j]=temp;
    }


//    @Override
//    public int[] sort(int[] sourceArray){
//        // 对 arr 进行拷贝，不改变参数内容
//        int[] arr = Arrays.copyOf(sourceArray, sourceArray.length);
//
//        return quickSort(arr, 0, arr.length - 1);
//    }
//
//    private int[] quickSort(int[] arr, int left, int right) {
//        if (left < right) {
//            int partitionIndex = partition(arr, left, right);
//            quickSort(arr, left, partitionIndex - 1);
//            quickSort(arr, partitionIndex + 1, right);
//        }
//        return arr;
//    }
//
//    private int partition(int[] arr, int left, int right) {
//        // 设定基准值（pivot）
//        int pivot = left;
//        int index = pivot + 1;
//        for (int i = index; i <= right; i++) {
//            if (arr[i] < arr[pivot]) {
//                swap(arr, i, index);
//                index++;
//            }
//        }
//        swap(arr, pivot, index - 1);
//        return index - 1;
//    }
//
//    private void swap(int[] arr, int i, int j) {
//        int temp = arr[i];
//        arr[i] = arr[j];
//        arr[j] = temp;
//    }


    public static void main(String[] args) {
        QuickSort quickSort = new QuickSort();
        int[] a = {1,5,4,3,2,9,7,8};
        int[] sort = quickSort.sort(a);
        for (int i : sort) {
            System.out.print(i+" ");
        }
    }
}
